package com.shop.controller;

import com.shop.common.SetMeta;
import com.shop.entity.Category;
import com.shop.exception.CategoryException;
import com.shop.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

@CrossOrigin
@RestController
public class CategoryController {
    @Autowired
    private CategoryService categoryService;

    /**
     * 商品分类数据列表
     * @param type
     * @param pagenum
     * @param pagesize
     * @return
     */
    @PreAuthorize("hasAuthority('149')")
    @GetMapping("/categories")
    public SetMeta selectCategory(@RequestParam(required = false) Integer type,
                                  @RequestParam(required = false) Integer pagenum,
                                  @RequestParam(required = false) Integer pagesize) {
        SetMeta setMeta = new SetMeta();
        try {
            if (pagenum == null || pagesize == null) {
                setMeta = categoryService.selectCategory(type);
            } else {
                setMeta = categoryService.selectPageCategory(type, pagenum, pagesize);
            }
        } catch (CategoryException e) {
            setMeta.setError("分类参数错误");
        }
        return setMeta;
    }

    /**
     * 添加分类
     * @param category
     * @return
     */
    @PreAuthorize("hasAuthority('122')")
    @PostMapping("/categories")
    public SetMeta<Category> addCategory(@RequestBody Category category) {
        SetMeta setMeta = new SetMeta();
        try {
            setMeta = categoryService.addCategory(category);
        } catch (CategoryException e) {
            setMeta.setError(e.getMessage());
        }
        return setMeta;
    }

    /**
     * 根据id查询分类
     * @param id
     * @return
     */
    @PreAuthorize("hasAuthority('149')")
    @GetMapping("/categories/{id}")
    public SetMeta<Category> selectById(@PathVariable Integer id) {
        return categoryService.selectById(id);
    }

    /**
     * 编辑提交分类
     * @param id
     * @param category
     * @return
     */
    @PreAuthorize("hasAuthority('160')")
    @PutMapping("/categories/{id}")
    public SetMeta<Category> updateCategory(@PathVariable Integer id,
                                            @RequestBody Category category) {
        return categoryService.updateCategory(id, category.getCat_name());
    }

    /**
     * 删除分类
     * @param id
     * @return
     */
    @PreAuthorize("hasAuthority('123')")
    @DeleteMapping("/categories/{id}")
    public SetMeta<Category> delete(@PathVariable Integer id) {
        return categoryService.delete(id);
    }
}
